﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;
using System.Data;
/// <summary>
/// Summary description for FileFunctions
/// </summary>
public class FileFunctions
{
	public FileFunctions()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public static string GenerateFileSaveIndex(string fileName, bool isTemp)
    {
        string fileExtension = Path.GetExtension(fileName);


        string command = "sp_tb_file_index_CreateNewFileIndex";

        if (isTemp)
        {
            command = "sp_tb_file_index_temp_CreateNewFileIndex";
        }
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        SqlCommand sqlCmd = new SqlCommand(command, sqlCon);
        sqlCon.Open();
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;


        sqlCmd.Parameters.Add("@fileName", SqlDbType.VarChar, 255);
        sqlCmd.Parameters.Add("@fileIndex", SqlDbType.UniqueIdentifier, 255);
        sqlCmd.Parameters.Add("@fileExtension", SqlDbType.VarChar, 10);
        sqlCmd.Parameters.Add("@result", SqlDbType.Int, 16);
        sqlCmd.Parameters["@fileIndex"].Direction = ParameterDirection.Output;
        sqlCmd.Parameters["@result"].Direction = ParameterDirection.Output;

        sqlCmd.Parameters["@fileName"].Value = fileName;
        sqlCmd.Parameters["@fileExtension"].Value = fileExtension;

        sqlCmd.ExecuteNonQuery();

        string fileSaveIndex = sqlCmd.Parameters["@fileIndex"].Value.ToString() + fileExtension;

        int result = 0;

        try
        {
            result = Convert.ToInt16(sqlCmd.Parameters["@result"].Value);
        }
        catch (Exception ex)
        {
            result = 0;
            throw new Exception("There was a problem generating the file save index");
        }



        sqlCon.Close();

        return fileSaveIndex;
    }

    
}
